package com.zrwl.poscloud.xo.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zrwl.poscloud.base.entity.Company;
import com.zrwl.poscloud.base.entity.Dept;
import com.zrwl.poscloud.base.entity.DeptAdminR;
import com.zrwl.poscloud.base.enums.EStatus;
import com.zrwl.poscloud.base.superI.SuperServiceImpl;
import com.zrwl.poscloud.commons.utils.ResultUtil;
import com.zrwl.poscloud.commons.utils.StringUtils;
import com.zrwl.poscloud.xo.global.MessageConf;
import com.zrwl.poscloud.xo.global.SQLConf;
import com.zrwl.poscloud.xo.global.SysConf;
import com.zrwl.poscloud.xo.mapper.DeptAdminRMapper;
import com.zrwl.poscloud.xo.service.AdminService;
import com.zrwl.poscloud.xo.service.CompanyService;
import com.zrwl.poscloud.xo.service.DeptAdminRService;
import com.zrwl.poscloud.xo.service.DeptService;
import com.zrwl.poscloud.xo.vo.AdminVO;
import com.zrwl.poscloud.xo.vo.DeptAdminRVO;
import com.zrwl.poscloud.xo.vo.DeptVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * 部门权限 服务实现类
 *
 * @author 刘思童 AutoGenerate
 * @date 2022-03-10
 */
@Service
public class DeptAdminRServiceImpl extends SuperServiceImpl<DeptAdminRMapper, DeptAdminR> implements DeptAdminRService {

    @Autowired
    private DeptAdminRService deptAdminRService;
    @Autowired
    private AdminService adminService;
    @Autowired
    private DeptService deptService;
    @Resource
    private DeptAdminRMapper deptAdminRMapper;
    @Autowired
    private CompanyService companyService;

    @Override
    public IPage<DeptAdminR> getPageList(DeptAdminRVO deptAdminRVO) {
        QueryWrapper<DeptAdminR> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(deptAdminRVO.getKeyword()) && !StringUtils.isEmpty(deptAdminRVO.getKeyword().trim())) {
            queryWrapper.like("name", deptAdminRVO.getKeyword().trim());
        }
        Page<DeptAdminR> page = new Page<>();
        page.setCurrent(deptAdminRVO.getCurrentPage());
        page.setSize(deptAdminRVO.getPageSize());
        queryWrapper.ne(SQLConf.STATUS, EStatus.DISABLED);
        queryWrapper.orderByDesc(SQLConf.CREATE_TIME);
        IPage<DeptAdminR> pageList = deptAdminRService.page(page, queryWrapper);
        List<DeptAdminR> list = pageList.getRecords();
        pageList.setRecords(list);
        return pageList;
    }

    @Override
    public List<DeptAdminR> getAllList(DeptAdminRVO deptAdminRVO) {
        QueryWrapper<DeptAdminR> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne(SQLConf.STATUS, EStatus.DISABLED);
        queryWrapper.orderByAsc(SQLConf.CREATE_TIME);
        List<DeptAdminR> list = deptAdminRService.list(queryWrapper);
        return list;
    }

    @Override
    public String add(DeptAdminRVO deptAdminRVO) {
        DeptAdminR entity = new DeptAdminR();
        BeanUtils.copyProperties(deptAdminRVO, entity, SysConf.STATUS);
        entity.insert();
        deptAdminRVO.setUid(entity.getUid());
        return ResultUtil.successWithMessage(MessageConf.INSERT_SUCCESS);
    }

    @Override
    public String edit(DeptAdminRVO deptAdminRVO) {
        DeptAdminR entity = deptAdminRService.getById(deptAdminRVO.getUid());
        BeanUtils.copyProperties(deptAdminRVO, entity);
        entity.setUpdateTime(new Date());
        entity.updateById();
        return ResultUtil.successWithMessage(MessageConf.UPDATE_SUCCESS);
    }

    @Override
    public String delete(DeptAdminRVO deptAdminRVO) {
        DeptAdminR entity = deptAdminRService.getById(deptAdminRVO.getUid());
        entity.setStatus(EStatus.DISABLED);
        entity.setUpdateTime(new Date());
        entity.updateById();
        return ResultUtil.successWithMessage(MessageConf.UPDATE_SUCCESS);
    }

    @Override
    public List<DeptVO> getAdminOwnDeptRoleListForTransferTree(DeptAdminRVO deptAdminRVO) {
        QueryWrapper<DeptAdminR> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("admin_uid", deptAdminRVO.getAdminUid());
        queryWrapper.eq("company_uid", deptAdminRVO.getCompanyUid());
        DeptAdminR deptAdminR = deptAdminRService.getOne(queryWrapper);
        if (deptAdminR == null) {
            DeptAdminR entity = new DeptAdminR();
            entity.setAdminUid(deptAdminRVO.getAdminUid());
            entity.setCompanyUid(deptAdminRVO.getCompanyUid());
            entity.setCompanyCode(deptAdminRVO.getCompanyCode());
            entity.setDeptRoleTree("[]");//初始化
            entity.setCreateAdminUid(adminService.getMe().getUid());
            entity.setStatus(EStatus.ENABLE);
            entity.setCreateTime(new Date());
            entity.setUpdateTime(new Date());
            entity.insert();
            deptAdminR = entity;
        }
        String deptRoleTree = deptAdminR.getDeptRoleTree();
        List<DeptVO> resultList = JSONObject.parseArray(deptRoleTree, DeptVO.class);
        return resultList;
    }

    @Override
    public List<DeptVO> getAdminNotOwnDeptRoleListForTransferTree(DeptAdminRVO deptAdminRVO) {
        List<DeptVO> sourceList = getAdminOwnDeptRoleListForTransferTree(deptAdminRVO);
        List<DeptVO> resultList = new ArrayList<>();
        DeptVO root = new DeptVO();
        root.setCompanyUid(deptAdminRVO.getCompanyUid());
        root.setName(deptAdminRVO.getCompanyName());
        root.setCompanyCode(deptAdminRVO.getCompanyCode());
        root.setLevel(0);
        root.setUid(deptAdminRVO.getCompanyUid());//充当一个uid和superUid功能测试是否影响
        resultList.add(root);
        deptService.setChildrenList(root);
        for (int i = 0; i < sourceList.size(); i++) {
            for (int j = 0; j < resultList.size(); j++) {
                if (sourceList.get(i).getUid().equals(resultList.get(j).getUid())) {
                    DeptVO temp = deleteRepeat(sourceList.get(i), resultList.get(j));
                    temp.setParentVO(null);
                    break;
                }
            }
        }
        for (int i = 0; i < resultList.size(); i++) {
            if (resultList.get(i).getChildrenList() == null || resultList.get(i).getChildrenList().size() == 0) {
                resultList.get(i).setParentVO(null);
                resultList.remove(i);
                i--;
            }
        }
        return resultList;
    }

    //递归删除重复节点
    public DeptVO deleteRepeat(DeptVO deptVO1, DeptVO deptVO2) {
        List<DeptVO> childrenList1 = deptVO1.getChildrenList();
        List<DeptVO> childrenList2 = deptVO2.getChildrenList();
        for (int i = 0; i < childrenList1.size(); i++) {
            for (int j = 0; j < childrenList2.size(); j++) {
                if (childrenList1.get(i).getUid().equals(childrenList2.get(j).getUid())) {
                    if (childrenList1.get(i).getChildrenList() != null && childrenList1.get(i).getChildrenList().size() != 0
                            && childrenList2.get(j).getChildrenList() != null && childrenList2.get(j).getChildrenList().size() != 0) {
                        childrenList2.get(j).setParentVO(deptVO2);
                        DeptVO temp = deleteRepeat(childrenList1.get(i), childrenList2.get(j));
                        deleteParents(temp);
                        temp.setParentVO(null);
                    } else {
                        if (childrenList2.get(j).getChildrenList() == null || childrenList2.get(j).getChildrenList().size() == 0) {
                            childrenList2.remove(j);
                            if (childrenList2.size() == 0) {
                                deptVO2.setChildrenList(null);
                            }
                        }
                    }
                }
            }
        }
        return deptVO2;
    }

    //递归删除空根节点
    void deleteParents(DeptVO me) {
        if (me.getChildrenList() == null || me.getChildrenList().size() == 0) {
            if (me.getParentVO() != null) {
                me.getParentVO().getChildrenList().remove(me);
                deleteParents(me.getParentVO());
            }
        }
    }

    @Override
    public String editAdminDeptRoleForTransferTree(DeptAdminRVO deptAdminRVO) {
        QueryWrapper<DeptAdminR> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("admin_uid", deptAdminRVO.getAdminUid());
        queryWrapper.eq("company_uid", deptAdminRVO.getCompanyUid());
        DeptAdminR entity = deptAdminRService.getOne(queryWrapper);
        entity.setDeptRoleTree(deptAdminRVO.getDeptRoleTree());
        entity.setUpdateTime(new Date());
        entity.updateById();
        return ResultUtil.successWithMessage(MessageConf.UPDATE_SUCCESS);
    }

    @Override
    public List<DeptVO> getAdminOwnDeptRoleList(DeptAdminRVO deptAdminRVO, Map<String, DeptVO> deptMap) {//这里需要锁防止重复调用还有类似的service也需要锁
        QueryWrapper<DeptAdminR> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("admin_uid", deptAdminRVO.getAdminUid());
        queryWrapper.eq("company_uid", deptAdminRVO.getCompanyUid());
        DeptAdminR deptAdminR = deptAdminRService.getOne(queryWrapper);
        if (deptAdminR == null) {
            DeptAdminR entity = new DeptAdminR();
            entity.setAdminUid(deptAdminRVO.getAdminUid());
            entity.setCompanyUid(deptAdminRVO.getCompanyUid());
            entity.setCompanyCode(deptAdminRVO.getCompanyCode());
            entity.setDeptRoleTree("");//初始化
            entity.setDeptRoleTreeCode("");//初始化
            entity.setCreateAdminUid(adminService.getMe().getUid());
            entity.setStatus(EStatus.ENABLE);
            entity.setCreateTime(new Date());
            entity.setUpdateTime(new Date());
            entity.insert();
            deptAdminR = entity;
        }
        List<String> uidList = Arrays.asList(deptAdminR.getDeptRoleTree().split(","));
        List<DeptVO> resultList = new ArrayList<>();
        DeptVO root = new DeptVO();
        root.setPermissionList(uidList);
        root.setCompanyUid(deptAdminRVO.getCompanyUid());
        root.setName(deptAdminRVO.getCompanyName());
        root.setCompanyCode(deptAdminRVO.getCompanyCode());
        root.setLevel(0);
        root.setSuperCompanyName("");
        root.setSuperCompanyFullName("");
        root.setUid(deptAdminRVO.getCompanyUid());//充当一个uid和superUid功能测试是否影响
        for (String item : uidList) {
            root.setPermission(true);
            if (item.equals(root.getUid())) {
                root.setPermission(false);
                break;
            }
        }
        deptMap.put(root.getCompanyCode(), root);
        resultList.add(root);
        deptService.setChildrenList(root, uidList, deptMap);
        return resultList;
    }

    @Override
    public String editAdminDeptRole(DeptAdminRVO deptAdminRVO) {
        QueryWrapper<DeptAdminR> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("admin_uid", deptAdminRVO.getAdminUid());
        queryWrapper.eq("company_uid", deptAdminRVO.getCompanyUid());
        DeptAdminR entity = deptAdminRService.getOne(queryWrapper);
        entity.setDeptRoleTree(deptAdminRVO.getDeptRoleTree());
        entity.setDeptRoleTreeCode(deptAdminRVO.getDeptRoleTreeCode());
        entity.setUpdateTime(new Date());
        entity.updateById();
        return ResultUtil.successWithMessage(MessageConf.UPDATE_SUCCESS);
    }

    @Override
    public String[] getMyDeptRoleTree() {
        AdminVO adminVO = adminService.getMe();
        String tree = deptAdminRMapper.getDeptRoleTreeByCompanyUidAndAdminUid(adminVO.getCompanyUid(), adminVO.getUid());
        return tree.split(",");
    }

    @Override
    public String[] getMyDeptRoleTreeName() {
        String[] myDeptRoleTree = getMyDeptRoleTree();
        if (myDeptRoleTree.length == 0 || myDeptRoleTree[0] == "") {
            throw new RuntimeException("该商户未配置部门");
        }
        StringBuilder name = new StringBuilder();
        for (String s : myDeptRoleTree) {
            Dept dept = deptService.getById(s);
            if (dept != null) {
                name.append(dept.getName()).append(",");
            }
        }
        return name != null ? name.toString().split(",") : null;
    }

    @Override
    public String[] getMyDeptRoleTreeName(String companyUid, String adminUid) {
        String[] myDeptRoleTree = getMyDeptRoleTree(companyUid, adminUid);
        if (myDeptRoleTree.length == 0 || "".equals(myDeptRoleTree[0])) {
            throw new RuntimeException("该商户未配置部门");
        }
        StringBuilder name = new StringBuilder();
        for (String s : myDeptRoleTree) {
            Dept dept = deptService.getById(s);
            if (dept != null) {
                name.append(dept.getName()).append(",");
            }
        }
        name = new StringBuilder(name.substring(0, name.length() - 1));
        return name != null ? name.toString().split(",") : null;
    }

    @Override
    public String[] getMyDeptRoleTree(String companyUid, String adminUid) {
        String tree = deptAdminRMapper.getDeptRoleTreeByCompanyUidAndAdminUid(companyUid, adminUid);
        if (tree == null) {
            throw new RuntimeException("该商户未配置部门");
        }
        return tree.split(",");
    }

    @Override
    public String[] getMyDeptRoleTreeCode() {
        AdminVO adminVO = adminService.getMe();
        String tree = deptAdminRMapper.getDeptRoleTreeCodeByCompanyUidAndAdminUid(adminVO.getCompanyUid(), adminVO.getUid());
        if (tree == null) {
            throw new RuntimeException("该商户未配置部门");
        }
        return tree.split(",");
    }

    @Override
    public String[] getMyDeptRoleTreeCode(String companyUid, String adminUid) {
        AdminVO adminVO = adminService.getMe();
        String tree = deptAdminRMapper.getDeptRoleTreeCodeByCompanyUidAndAdminUid(companyUid, adminUid);
        if (tree == null) {
            throw new RuntimeException("该商户未配置部门");
        }
        return tree.split(",");
    }

    @Override
    public List<String> getMyCodeByUid() {
        String[] tree = getMyDeptRoleTree();
        List<String> deptCode = deptAdminRMapper.getMyDeptCodeByUid(tree);
        List<String> companyCode = deptAdminRMapper.getMyCompanyCodeByUid(tree);
        List<String> list = new ArrayList<>();
        if (!companyCode.isEmpty()) {
            list = companyCode;
        }
        if (!deptCode.isEmpty()) {
            if (list.isEmpty()) {
                list = deptCode;
            } else {
                list.addAll(deptCode);
            }
        }
        return list;
    }

    @Override
    public Map<String, DeptVO> getMyDeptRoleTreeEntity(String companyUid, String adminUid) {
        String tree = deptAdminRMapper.getDeptRoleTreeByCompanyUidAndAdminUid(companyUid, adminUid);
        Map<String, DeptVO> map = new HashMap<>();
        String[] split = tree.split(",");
        for (String uid : split) {
            DeptVO entity = new DeptVO();
            Company company = companyService.getById(uid);
            if (company != null) {
                entity.setUid(company.getUid());
                entity.setName(company.getShortName());
                entity.setCompanyCode(company.getCompanyCode());
                entity.setLevel(0);
            }
            Dept dept = deptService.getById(uid);
            if (dept != null) {
                entity.setUid(dept.getUid());
                entity.setName(dept.getName());
                entity.setCompanyCode(dept.getCompanyCode());
                entity.setLevel(dept.getLevel());
            }
            entity.setSuperCompanyName(deptAdminRMapper.getCompanySuperNameByCode(entity.getCompanyCode(), entity.getLevel()));
            map.put(entity.getName(), entity);
        }
        return map;
    }

    @Override
    public DeptAdminR getByCompany(String adminUid, String companyUid) {
        QueryWrapper<DeptAdminR> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("admin_uid", adminUid);
        queryWrapper.eq("company_uid", companyUid);
        DeptAdminR entity = deptAdminRService.getOne(queryWrapper);
        return entity;
    }
}
